import json
import os
import sys
import random
from constants import * 
os.chdir(os.path.dirname(os.path.abspath(__file__)))
class GameMap:
    def __init__(self, width, height , cell_size):
        self.width = width
        self.height = height
        self.cell_size = cell_size
        self.walls = []
        self.obstacles = set()
    
    def is_obstacle(self, position):
        return position in self.obstacles
    
    def add_obstacle(self, position):
        self.obstacles.add(position)
    
    @staticmethod
    def load_maps():
        maps = []
        for i in range(7):
            filename = f"../maps/map{i+1}.json"
            with open(filename, "r") as f:
                data = json.load(f)
            
            map_width = data["width"]
            map_height = data["height"]
            map_cell_size = data["cell_size"]
            game_map = GameMap(map_width, map_height,map_cell_size)
            
            for position in data["obstacles"]:
                game_map.add_obstacle(tuple(position))
            
            maps.append(game_map)
        
        return maps
    
    def get_random_position(self,snake_positions):
        while True:
            x = random.randint(0, self.height - 1)
            y = random.randint(0, self.width - 1) 
            if  not self.is_obstacle((x,y)) and (x,y) not in snake_positions :
                return (x,y)


